package com.eeds.service.user.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ctc.wstx.util.DataUtil;
import com.eeds.common.constant.DictionaryConstants;
import com.eeds.common.constant.RedisConstant;
import com.eeds.common.constant.SystemConstants;
import com.eeds.common.enums.SmsType;
import com.eeds.common.enums.StatusEnum;
import com.eeds.common.model.PageInfo;
import com.eeds.common.model.RespEnum;
import com.eeds.common.table.UserBaseInfoEntity;
import com.eeds.common.table.UserRoleAssEntity;
import com.eeds.crypto.AESUtil;
import com.eeds.crypto.Decript;
import com.eeds.dao.UserBaseInfoDao;
import com.eeds.dao.UserRoleAssDao;
import com.eeds.date.DateUtil;
import com.eeds.exception.AuthException;
import com.eeds.exception.ServerException;
import com.eeds.json.GsonUtil;
import com.eeds.model.role.req.ReqGetRoleInfoListVO;
import com.eeds.model.user.req.*;
import com.eeds.model.user.res.ResGetUserInfoListVO;
import com.eeds.model.user.res.ResGetUserInfoVO;
import com.eeds.model.user.res.ResLoginVo;
import com.eeds.model.user.res.ResRefreshTokenVo;
import com.eeds.para.ParametersUtil;
import com.eeds.redis.StringRedisUtil;
import com.eeds.service.role.RoleService;
import com.eeds.service.user.UserService;
import com.eeds.token.TokenUitl;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.util.List;

/**
 * @author Flying
 * @Description
 * @date 14:42 2018-08-24
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserBaseInfoDao userBaseInfoDao;

    @Autowired
    private StringRedisUtil redisUtil;

    @Autowired
    private UserRoleAssDao userRoleAssDao;

    /**
     * 用户登陆
     *
     * @param reqLoginVo
     * @return
     */
    /**
     * 用户登陆
     *
     * @param reqLoginVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResLoginVo login(ReqLoginVo reqLoginVo) {
        ResLoginVo resLoginVo = commonLogin(reqLoginVo,0);
        return resLoginVo;
    }

    private ResLoginVo commonLogin(ReqLoginVo reqLoginVo,Integer type){
        ResLoginVo resLoginVo = new ResLoginVo();
        UserBaseInfoEntity wrapper = new UserBaseInfoEntity();
        wrapper.setUserName(reqLoginVo.getUserName());
        UserBaseInfoEntity userBaseInfo = userBaseInfoDao.selectOne(wrapper);
        if(userBaseInfo == null){
            throw new ServerException(RespEnum.NO_THIS_USER);
        }
        String password = Decript.encrypt(reqLoginVo.getPassword(),userBaseInfo.getUserSalt());
        if(!userBaseInfo.getPassword().equals(password)){
            throw new ServerException(RespEnum.USER_PWD_ERROR);
        }
        resLoginVo.setIdUserBaseInfo(userBaseInfo.getIdUserBaseInfo());
        resLoginVo.setNickName(userBaseInfo.getNickName());
        resLoginVo.setUserName(userBaseInfo.getUserName());
        resLoginVo.setCreateTime(userBaseInfo.getCreateTime());
        resLoginVo.setUserPhone(userBaseInfo.getUserPhone());
        resLoginVo.setUpdateTime(userBaseInfo.getUpdateTime());
        resLoginVo.setUserAge(userBaseInfo.getUserAge());
        resLoginVo.setAccessToken(TokenUitl.getToken());

        redisUtil.set(RedisConstant.USER_ACCESS_RECORD_TOKEN + userBaseInfo.getIdUserBaseInfo(), resLoginVo.getAccessToken(),60 * 60 * 24 * 7);
        redisUtil.set(RedisConstant.USER_ACCESS_TOKEN+ resLoginVo.getAccessToken(),userBaseInfo.getIdUserBaseInfo().toString() ,60 * 60 * 24 * 7);
        ReqGetRoleInfoListVO reqGetRoleInfoListVO = new ReqGetRoleInfoListVO();
        reqGetRoleInfoListVO.setUserId(userBaseInfo.getIdUserBaseInfo());

        Wrapper<UserRoleAssEntity> wrapper1 = new EntityWrapper<>();
        wrapper1.eq("idx_user_base_info",userBaseInfo.getIdUserBaseInfo());
        List<UserRoleAssEntity> userRoleAssList = userRoleAssDao.selectList(wrapper1);
        redisUtil.set(RedisConstant.USER_ACCESS_ROLE +  userBaseInfo.getIdUserBaseInfo(), GsonUtil.GsonString(userRoleAssList),60 * 60 * 24 * 7);
        if(type == 1){
            Boolean falg = false;
                for (UserRoleAssEntity userRoleAssEntity : userRoleAssList) {
                    if(userRoleAssEntity.getIdxUserRole() == 1L){
                        falg = true;
                    }
                }
                if(!falg) {
                    throw new AuthException(RespEnum.USER_AUTHENTICATION);
                }
        }
        return resLoginVo;
    }


    /**
     * 登陆PC接口
     *
     * @param reqLoginVo
     * @return
     */
    @Override
    public ResLoginVo loginPC(ReqLoginVo reqLoginVo) {
        ResLoginVo resLoginVo = commonLogin(reqLoginVo,1);

        return resLoginVo;
    }

    /**
     * 修改用户信息
     *
     * @param reqUpdateUserInfoVO
     * @return
     */
    @Override
    @Transactional
    public Integer updateUserInfo(ReqUpdateUserInfoVO reqUpdateUserInfoVO) {
        UserBaseInfoEntity userBaseInfoEntity  = new UserBaseInfoEntity();
        userBaseInfoEntity.setNickName(reqUpdateUserInfoVO.getNickName());
        userBaseInfoEntity.setUserName(reqUpdateUserInfoVO.getUserName());
        userBaseInfoEntity.setUserAge(reqUpdateUserInfoVO.getUserAge());
        userBaseInfoEntity.setStatus(reqUpdateUserInfoVO.getStatus());
        userBaseInfoEntity.setUserPhone(reqUpdateUserInfoVO.getUserPhone());
        userBaseInfoEntity.setIdUserBaseInfo(reqUpdateUserInfoVO.getUserBaseInfoId());
        userBaseInfoDao.updateById(userBaseInfoEntity);


        Wrapper<UserRoleAssEntity> wrapper = new EntityWrapper();
        wrapper.eq("idx_user_base_info",userBaseInfoEntity.getIdUserBaseInfo());
        userRoleAssDao.delete(wrapper);

        UserRoleAssEntity userRoleAssEntity = new UserRoleAssEntity();
        userRoleAssEntity.setIdxUserBaseInfo(userBaseInfoEntity.getIdUserBaseInfo());
        userRoleAssEntity.setIdxUserRole(reqUpdateUserInfoVO.getUserRoleId());
        userRoleAssDao.insert(userRoleAssEntity);
        return 1;
    }

    /**
     * 获取用户信息列表
     *
     * @param reqGetUserInfoListVO
     * @return
     */
    @Override
    public PageInfo<ResGetUserInfoListVO> getUserInfoList(ReqGetUserInfoListVO reqGetUserInfoListVO) {
        PageInfo<ResGetUserInfoListVO> pageInfo = new PageInfo<>(reqGetUserInfoListVO);
        pageInfo.setData(userBaseInfoDao.getUserInfoList(pageInfo,reqGetUserInfoListVO));
        pageInfo.setTotalResult(userBaseInfoDao.getUserInfoListTotalCount(reqGetUserInfoListVO));
        return pageInfo;
    }

    /**
     * 删除用户
     *
     * @param reqDeleteUserVO
     * @return
     */
    @Override
    public Integer deleteUser(ReqDeleteUserVO reqDeleteUserVO) {
        UserBaseInfoEntity userBaseInfoEntity  = new UserBaseInfoEntity();
        userBaseInfoEntity.setIdUserBaseInfo(reqDeleteUserVO.getUserBaseInfoId());
        userBaseInfoEntity.setStatus(0);
        userBaseInfoDao.updateById(userBaseInfoEntity);
        return 1;
    }

    /**
     * 修改用户密码
     *
     * @param reqUpdateUserPasswordVO
     * @return
     */
    @Override
    public Integer updateUserPassword(ReqUpdateUserPasswordVO reqUpdateUserPasswordVO) {
        UserBaseInfoEntity userBaseInfo = userBaseInfoDao.selectById(reqUpdateUserPasswordVO.getUserBaseInfoId());
        if(ParametersUtil.isNull(userBaseInfo)){
            throw  new ServerException(RespEnum.NO_THIS_USER);
        }
        if(!userBaseInfo.getPassword().equals(Decript.encrypt(reqUpdateUserPasswordVO.getOldUserPassword(),userBaseInfo.getUserSalt()))){
            throw  new ServerException(RespEnum.OLD_PASSWORD_ERROR);
        }
        UserBaseInfoEntity userBaseInfoEntity  = new UserBaseInfoEntity();
        userBaseInfoEntity.setUserSalt(userBaseInfo.getUserSalt());
        userBaseInfoEntity.setPassword(Decript.encrypt(reqUpdateUserPasswordVO.getUserPassword(),userBaseInfoEntity.getUserSalt()));
        userBaseInfoEntity.setIdUserBaseInfo(reqUpdateUserPasswordVO.getUserBaseInfoId());
        userBaseInfoDao.updateById(userBaseInfoEntity);
        return null;
    }

    /**
     * 添加用户信息
     *
     * @param reqAddUserInfoVO
     * @return
     */
    @Override
    @Transactional
    public Integer addUserInfo(ReqAddUserInfoVO reqAddUserInfoVO) {
        UserBaseInfoEntity userBaseInfoEntity  = new UserBaseInfoEntity();
        userBaseInfoEntity.setNickName(reqAddUserInfoVO.getNickName());
        userBaseInfoEntity.setUserName(reqAddUserInfoVO.getUserName());
        userBaseInfoEntity.setUserAge(reqAddUserInfoVO.getUserAge());
        userBaseInfoEntity.setStatus(reqAddUserInfoVO.getStatus());
        userBaseInfoEntity.setUserPhone(reqAddUserInfoVO.getUserPhone());
        userBaseInfoEntity.setUserSalt(SystemConstants.SYS_DICT_CACHE_KEY+System.currentTimeMillis());
        userBaseInfoEntity.setPassword(Decript.encrypt(SystemConstants.DEFAULT_PASSWORD,userBaseInfoEntity.getUserSalt()));
        userBaseInfoEntity.setCreateTime(DateUtil.nowDate());
        userBaseInfoDao.insert(userBaseInfoEntity);

        UserRoleAssEntity userRoleAssEntity = new UserRoleAssEntity();
        userRoleAssEntity.setIdxUserBaseInfo(userBaseInfoEntity.getIdUserBaseInfo());
        userRoleAssEntity.setIdxUserRole(reqAddUserInfoVO.getUserRoleId());
        userRoleAssDao.insert(userRoleAssEntity);

        return 1;
    }

    /**
     * 重置用户密码
     *
     * @param reqResetUserPasswordVO
     * @return
     */
    @Override
    public Integer resetUserPassword(ReqResetUserPasswordVO reqResetUserPasswordVO) {
        UserBaseInfoEntity userBaseInfo = userBaseInfoDao.selectById(reqResetUserPasswordVO.getUserBaseInfoId());
        UserBaseInfoEntity userBaseInfoEntity  = new UserBaseInfoEntity();
        userBaseInfoEntity.setUserSalt(userBaseInfo.getUserSalt());
        userBaseInfoEntity.setPassword(Decript.encrypt(SystemConstants.DEFAULT_PASSWORD,userBaseInfoEntity.getUserSalt()));
        userBaseInfoEntity.setIdUserBaseInfo(reqResetUserPasswordVO.getUserBaseInfoId());
        userBaseInfoDao.updateById(userBaseInfoEntity);
        return 1;
    }

    /**
     * 获取用户信息
     *
     * @param reqGetUserInfoVO
     * @return
     */
    @Override
    public ResGetUserInfoVO getUserInfo(ReqGetUserInfoVO reqGetUserInfoVO) {
        ResGetUserInfoVO resGetUserInfoVO = new ResGetUserInfoVO();
        UserBaseInfoEntity userBaseInfoEntity = userBaseInfoDao.selectById(reqGetUserInfoVO.getUserBaseInfoId());
        resGetUserInfoVO.setNickName(userBaseInfoEntity.getNickName());
        resGetUserInfoVO.setStatus(userBaseInfoEntity.getStatus());
        resGetUserInfoVO.setUserAge(userBaseInfoEntity.getUserAge());
        resGetUserInfoVO.setUserBaseInfoId(userBaseInfoEntity.getIdUserBaseInfo());
        resGetUserInfoVO.setUserName(userBaseInfoEntity.getUserName());
        resGetUserInfoVO.setUserPhone(userBaseInfoEntity.getUserPhone());
        UserRoleAssEntity wrapper  = new UserRoleAssEntity();
        wrapper.setIdxUserBaseInfo(userBaseInfoEntity.getIdUserBaseInfo());
        UserRoleAssEntity userRoleAssEntity = userRoleAssDao.selectOne(wrapper);
        if(ParametersUtil.isNotNull(userRoleAssEntity)){
            resGetUserInfoVO.setUserRoleId(userRoleAssEntity.getIdxUserRole());
        }
        return resGetUserInfoVO;
    }

    /**
     * 获取用户信息所有列表
     *
     * @return
     */
    @Override
    public List<ResGetUserInfoListVO> getUserInfoListAll() {
        return userBaseInfoDao.getUserInfoList(null,null);
    }


}
